import React, { useState, useEffect } from 'react';
import styled from 'styled-components';
import { Card } from 'antd';
import { API_BASE_URL } from '../config';

const Container = styled.div`
  display: flex;
  padding: 24px;
  min-height: 100vh;
  background: #001529;
  gap: 24px;
`;

const VideoContainer = styled.div`
  flex: 2;
  display: flex;
  justify-content: center;
  align-items: center;
  background: rgba(0, 0, 0, 0.5);
  border-radius: 8px;
  overflow: hidden;
  min-height: 600px;
  
  video {
    width: 100%;
    height: 100%;
    object-fit: cover;
  }

  .error-message {
    color: white;
    font-size: 20px;
    text-align: center;
    padding: 20px;
  }
`;

const MessagePanel = styled(Card)`
  flex: 1;
  max-width: 400px;
  height: calc(100vh - 48px);
  background: rgba(255, 255, 255, 0.95);
  
  .ant-card-head-title {
    font-size: 24px;
  }
  
  .ant-card-body {
    height: calc(100% - 57px);
    overflow-y: auto;
    padding: 24px;
    font-size: 18px;
  }
`;

const MessageItem = styled.div`
  padding: 12px;
  margin-bottom: 12px;
  background: rgba(0, 47, 167, 0.1);
  border-radius: 6px;
  font-size: 20px;
  
  &.warning {
    background: rgba(255, 82, 82, 0.1);
    color: #ff5252;
  }
`;

const MonitoringRoom: React.FC = () => {
  const [messages, setMessages] = useState<string[]>([]);
  const [videoError, setVideoError] = useState(false);

  useEffect(() => {
    const fetchMessages = async () => {
      try {
        const response = await fetch(`${API_BASE_URL}/api/monitor/messages`);
        const data = await response.json();
        if (data.messages) {
          setMessages(data.messages);
        }
      } catch (error) {
        console.error('获取监控消息失败:', error);
      }
    };

    fetchMessages();
    const interval = setInterval(fetchMessages, 3000);
    return () => clearInterval(interval);
  }, []);

  const handleVideoError = () => {
    console.error('视频加载失败');
    setVideoError(true);
  };

  return (
    <Container>
      <VideoContainer>
        {!videoError ? (
          <video 
            autoPlay 
            loop 
            muted 
            onError={handleVideoError}
          >
            <source src="/video/demo.mp4" type="video/mp4" />
            您的浏览器不支持视频播放。
          </video>
        ) : (
          <div className="error-message">
            视频加载失败，请检查文件路径或格式是否正确
          </div>
        )}
      </VideoContainer>
      <MessagePanel title="监控消息">
        {messages.map((msg, index) => (
          <MessageItem 
            key={index}
            className={msg.includes('警告') || msg.includes('陌生人') ? 'warning' : ''}
          >
            {msg}
          </MessageItem>
        ))}
      </MessagePanel>
    </Container>
  );
};

export default MonitoringRoom;
